package cn.i7baozh.provider.hystrix.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.i7baozh.provider.hystrix.service.PaymentService;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Title:
 * @Description:
 * @author: baoqi.zhang
 * @date: 2022/4/9 20:52
 */
@Service
public class PaymentServiceImpl implements PaymentService {

    public String paymentInfoOk(Integer id) {
        return "线程池：" + Thread.currentThread().getName() + " payment ok " + id;
    }

    /**
     * @HystrixCommand 注解需要在主启动类中加入 @EnableCircuitBreaker 才会生效
     * @param id
     * @return
     * @see HystrixPropertiesManager
     * @see HystrixCommandProperties
     */
    @HystrixCommand(fallbackMethod = "paymentInfoFallBack", commandProperties = {
            @HystrixProperty(name = HystrixPropertiesManager.EXECUTION_ISOLATION_THREAD_TIMEOUT_IN_MILLISECONDS, value = "3000")
    })
    public String paymentInfoError(Integer id) {
        // 错误 超时 都会触发降级
//        int age = 10 / 0;
        int timeOutSecond = 5;
        try {
            TimeUnit.SECONDS.sleep(timeOutSecond);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池：" + Thread.currentThread().getName() + " paymentInfoError" + id + " 耗时， 秒";

    }

    /**
     * 测试服务熔断
     * 熔断的缺省配置为 5秒20次失败
     *
     * @param id
     * @see HystrixCommandProperties
     * @return
     */
    @Override
    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback", commandProperties = {
            //是否开启断路器
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ENABLED, value = "true"),
            //请求次数
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_REQUEST_VOLUME_THRESHOLD, value = "10"),
            //时间窗口期 时间范围
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS, value = "10000"),
            //失败率达到多少后跳闸
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ERROR_THRESHOLD_PERCENTAGE, value = "60"),

            //因此整个配置表达的意思是： 如果在10秒钟 10次请求中错误率达到60% 则熔断
    })
    public String paymentCircuitBreaker(Integer id) {
        if (id < 0) {
            throw new RuntimeException("id不能为复数!");
        }
        String serialNum = IdUtil.simpleUUID();
        return "thread:" + Thread.currentThread().getName() + " 流水:" + serialNum;
    }
    public String paymentCircuitBreaker_fallback(Integer id) {
        return "熔断了， thread:" + Thread.currentThread().getName() + " id不能为复数";
    }
    public String paymentInfoFallBack(Integer id) {
        return "当前超过时长，服务开始降级，" + id;
    }
}
